package com.education.platform.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.education.platform.common.ResultCode;
import com.education.platform.entity.Conversation;
import com.education.platform.entity.User;
import com.education.platform.exception.BusinessException;
import com.education.platform.mapper.ConversationMapper;
import com.education.platform.mapper.UserMapper;
import com.education.platform.service.ConversationService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 会话服务实现类
 *
 * @author education-platform
 * @since 2024-10-07
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class ConversationServiceImpl implements ConversationService {

    private final ConversationMapper conversationMapper;

    private final UserMapper userMapper;

    @Override
    @Transactional
    public String createPrivateConversation(Long user1Id, Long user2Id) {
        // 检查是否已存在私聊会话
        Conversation existing = conversationMapper.selectPrivateConversation(user1Id, user2Id);
        if (existing != null) {
            return existing.getId();
        }

        // 创建新的私聊会话
        String conversationId = IdUtil.simpleUUID();
        Conversation conversation = new Conversation();
        conversation.setId(conversationId);
        conversation.setType(Conversation.Type.PRIVATE.name());
        
        List<Long> participants = List.of(user1Id, user2Id);
        conversation.setParticipants(JSONUtil.toJsonStr(participants));
        
        conversationMapper.insert(conversation);
        log.info("创建私聊会话成功, ID: {}, 参与者: {}", conversationId, participants);
        
        return conversationId;
    }

    @Override
    @Transactional
    public String createGroupConversation(String name, String avatar, List<Long> userIds) {
        if (userIds.size() < 2) {
            throw new BusinessException(ResultCode.SYSTEM_ERROR);
        }

        String conversationId = IdUtil.simpleUUID();
        Conversation conversation = new Conversation();
        conversation.setId(conversationId);
        conversation.setType(Conversation.Type.GROUP.name());
        conversation.setName(name);
        conversation.setAvatar(avatar);
        conversation.setParticipants(JSONUtil.toJsonStr(userIds));
        
        conversationMapper.insert(conversation);
        log.info("创建群聊会话成功, ID: {}, 名称: {}, 参与者数量: {}", conversationId, name, userIds.size());
        
        return conversationId;
    }

    @Override
    public Conversation getConversationById(String id) {
        Conversation conversation = conversationMapper.selectById(id);
        if (conversation == null) {
            throw new BusinessException(ResultCode.NOT_FOUND);
        }
        return conversation;
    }
    
    @Override
    public Conversation getConversationDetailWithUserInfo(String id, Long currentUserId) {
        Conversation conversation = conversationMapper.selectById(id);
        if (conversation == null) {
            throw new BusinessException(ResultCode.NOT_FOUND);
        }
        
        // 如果是私聊，填充对方用户信息
        if ("PRIVATE".equals(conversation.getType())) {
            List<Long> participants = getParticipantsFromJson(conversation.getParticipants());
            Long otherUserId = participants.stream()
                    .filter(userId -> !userId.equals(currentUserId))
                    .findFirst()
                    .orElse(null);
            
            if (otherUserId != null) {
                conversation.setOtherUserId(otherUserId);
                
                // 获取对方用户信息
                User otherUser = userMapper.selectById(otherUserId);
                if (otherUser != null) {
                    conversation.setOtherUserName(otherUser.getUsername());
                    conversation.setOtherUserAvatar(otherUser.getAvatarUrl());
                }
            }
        }
        
        return conversation;
    }

    @Override
    public IPage<Conversation> getUserConversationPage(Page<Conversation> page, Long userId) {
        return conversationMapper.selectUserConversationPage(page, userId);
    }

    @Override
    public List<Conversation> getUserConversations(Long userId) {
        return conversationMapper.selectUserConversations(userId);
    }

    @Override
    public Conversation getPrivateConversation(Long user1Id, Long user2Id) {
        return conversationMapper.selectPrivateConversation(user1Id, user2Id);
    }

    @Override
    @Transactional
    public void updateConversation(String conversationId, String name, String avatar) {
        Conversation conversation = getConversationById(conversationId);
        
        if (name != null) {
            conversation.setName(name);
        }
        if (avatar != null) {
            conversation.setAvatar(avatar);
        }
        
        conversationMapper.updateById(conversation);
        log.info("更新会话信息成功, ID: {}", conversationId);
    }

    @Override
    @Transactional
    public void addParticipant(String conversationId, Long userId) {
        Conversation conversation = getConversationById(conversationId);
        
        List<Long> participants = getParticipantsFromJson(conversation.getParticipants());
        if (!participants.contains(userId)) {
            participants.add(userId);
            conversation.setParticipants(JSONUtil.toJsonStr(participants));
            conversationMapper.updateById(conversation);
            log.info("添加会话参与者成功, 会话: {}, 用户: {}", conversationId, userId);
        }
    }

    @Override
    @Transactional
    public void removeParticipant(String conversationId, Long userId) {
        Conversation conversation = getConversationById(conversationId);
        
        List<Long> participants = getParticipantsFromJson(conversation.getParticipants());
        if (participants.remove(userId)) {
            conversation.setParticipants(JSONUtil.toJsonStr(participants));
            conversationMapper.updateById(conversation);
            log.info("移除会话参与者成功, 会话: {}, 用户: {}", conversationId, userId);
        }
    }

    @Override
    public boolean isParticipant(String conversationId, Long userId) {
        return conversationMapper.isParticipant(conversationId, userId);
    }

    @Override
    public List<Long> getParticipants(String conversationId) {
        return conversationMapper.selectParticipants(conversationId);
    }

    @Override
    @Transactional
    public void deleteConversation(String conversationId, Long userId) {
        // 检查权限
        if (!isParticipant(conversationId, userId)) {
            throw new BusinessException(ResultCode.FORBIDDEN);
        }
        
        conversationMapper.deleteById(conversationId);
        log.info("删除会话成功, ID: {}", conversationId);
    }

    /**
     * 从JSON字符串解析参与者列表
     */
    private List<Long> getParticipantsFromJson(String participantsJson) {
        if (participantsJson == null || participantsJson.isEmpty()) {
            return new ArrayList<>();
        }
        
        try {
            JSONArray jsonArray = JSONUtil.parseArray(participantsJson);
            return jsonArray.toList(Long.class);
        } catch (Exception e) {
            log.error("解析参与者列表失败: {}", participantsJson, e);
            return new ArrayList<>();
        }
    }
}
